<template>
  <div class="app-container">
    <el-form ref="placeCodeForm" v-loading="formLoading" :rules="rules" :model="form" label-position="top">
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="LOGO" prop="logo" style="width: 800px">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.logo" :src="form.logo" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="培训机构" prop="company" style="width: 200px">
            <el-input v-model="form.company" placeholder="请输入培训机构" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="地址" prop="transaddress" style="width: 400px">
            <div style="display: flex;">
              <el-input v-model="form.transaddress" placeholder="请选择地址" disabled  />
              <el-button size="mini" style="margin-left: 10px" icon="el-icon-position" type="primary" @click="showMap=true">选择位置</el-button>
            </div>
            <el-dialog title="选择位置" v-if="showMap" :visible.sync="showMap" width="40%" :append-to-body="true" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true" top="5vh" >
              <iframe id="mapPage" style="width: 100%;height: 500px" frameborder=0
                      src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=RSQBZ-R2NER-KFMWS-W6OZN-UXMTE-H4BIF&referer=91885App">
              </iframe>
              <span slot="footer" class="dialog-footer">
            <el-button type="primary" class="primary"  @click="showMap = false">确 定</el-button>
          </span>
            </el-dialog>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="联系电话" prop="mobile" style="width: 200px">
            <el-input v-model="form.mobile" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="管理后台账号" prop="userName" style="width: 400px">
            <el-input v-if="!isEdit" v-model="form.userName" placeholder="密码默认123456，学校管理员登录自行修改" clearable  />
            <el-input v-if="isEdit" v-model="form.userName" placeholder="密码默认123456，学校管理员登录自行修改" clearable  disabled="disabled"/>

          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="培训资质" prop="logo" style="width: 800px">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess2"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.qualifications" :src="form.qualifications" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row type="flex" :gutter="20">
        <el-col :span="24">
          <el-form-item label="培训描述" prop="Abstract">
            <div class="container">
              <Toolbar :editor="editor" :default-config="toolbarConfig" :mode="mode"/>
              <Editor v-model="form.describer" :default-config="editorConfig" :mode="mode" @onCreated="onCreated"/>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {editTrainApi, getTrainByIdApi} from '@/api/trainCode'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {uploadApi} from "@/api/user";
import axios from "axios";

export default {
  components: {Editor, Toolbar},
  name: 'PlaceCodeDetail',
  data() {
    return {
      editor: null,
      category: [],
      showMap:false,
      //期望职位级联选择器配置
      optionProps: {
        value: 'id',
        label: 'jobTitle',
        children: 'subLevelModelList',
        multiple: true
      },
      typeList:[],
      specialityList: [],
      toolbarConfig: {
        excludeKeys: [
          // 排除菜单组，写菜单组 key 的值即可
          'group-video' // 去掉视频
        ]
      },
      editorConfig: { MENU_CONF: {
          // 配置上传图片
          uploadImage: {
            customUpload: this.uploadImageMe // this.uploadImageMe 是 methods 中的一个普通方法
          },
        },
        placeholder: ''
      },
      mode: 'default',
      uploadUrl: process.env.VUE_APP_UPLOAD_API,
      dialogImageUrl: '',
      dialogVisible: false,
      isEdit: false,
      form: {
        id: null,
        trainName: '',
        company: '',
        trainTime: '',
        transaddress: '',
        describer: '',
        logo: '',
        latitude: '',
        longitude: '',
        qualifications: '',
        userName: '',
        mobile: '',
      },
      rules: {
        label: [{required: true, trigger: 'blur', message: '请输入培训种类'}],
        company: [{required: true, trigger: 'blur', message: '请输入培训机构'}],
        trainTime: [{required: true, trigger: 'blur', message: '请选择培训时间'}],
        transaddress: [{required: true, trigger: 'blur', message: '请输入培训地址'}],
        describer: [{required: true, trigger: 'blur', message: '请输入培训描述'}],
        userName: [{required: true, trigger: 'blur', message: '请输入管理员账号'}],
      },
      formLoading: false,
      placeTypeLoading: true,
      placeTypeOption: [],
      keywordList: [],
      ambiguityKeywordArray: '',
      eventPlanForm: {
        matchKeywordArray: [],
        ambiguityKeywordArray: [],
      },
    }
  },
  props: ['id', 'closeDialog'],
  methods: {
    //上传文件配置
    uploadImageMe(file, insertFn){
      console.log(file)
      // file 即选中的文件
      // 自己实现上传，并得到图片 url alt href
      let name = file.name;
      let suffix = file.type.split("/")[1];
      name = name + '.' + suffix;
      let formdata = new FormData()
      formdata.append("file", file)
      //上传方法
      uploadApi(formdata).then(res => {
        console.log(res)
        // 最后插入图片
        insertFn(res , res, res )
      })

    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    handleAvatarSuccess(res, file) {

      this.form.logo = res.data;
    },
    handleAvatarSuccess2(res, file) {

      this.form.qualifications = res.data;
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isLt2M;
    },

    submit() {
      this.$refs.placeCodeForm.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            text: '提交中'
          })
          if (this.form.id == null) {
            this.form.id = 0;
          }
          const form = JSON.parse(JSON.stringify(this.form));
          editTrainApi(form).then((res) => {
            this.$message.success('保存成功');
            this.closeDialog(0);
          }).catch((e) => {
            this.$message.error('保存失败');
          }).finally(() => {
            loading.close();
          })
        } else {
          return false
        }
      })
    },

    getDetail() {
      this.formLoading = true;
      getTrainByIdApi({id: this.id}).then((res) => {
        this.form.logo = res.logo
        this.form.company = res.company;
        this.form.describer = res.describer;
        this.form.id = res.id;
        this.form.mobile = res.mobile;
        this.form.state = res.state;
        this.form.transaddress = res.transaddress;
        this.form.qualifications = res.qualifications
        this.form.userName = res.userName
        if(res.userName)
        {
            this.isEdit = true
        }
      }).finally(() => {
        this.formLoading = false;
      })
    },
  },
  mounted() {
    window.addEventListener('message', (event) =>{
      // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
      let loc = event.data;
      if (loc && loc.module == 'locationPicker') {//防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
        this.form.latitude=loc.latlng.lat;
        this.form.longitude=loc.latlng.lng;
        this.form.transaddress=loc.poiname
        axios.get(`https://apis.map.qq.com/ws/geocoder/v1/?location=${loc.latlng.lat},${loc.latlng.lng}&key=RSQBZ-R2NER-KFMWS-W6OZN-UXMTE-H4BIF`).then((res)=>{
          console.log(res);
        })
      }
    }, false);
    if (this.id) {
      this.getDetail();
    }
  },
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },

}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #c5c5c5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}
</style>
<style scoped>
/*
*让select撑开
*/
.el-select, .el-cascader {
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #c5c5c5;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
